package cn.com.yusys.yusp.custManager.service;

import cn.com.yusys.yusp.admin.Utils.BlockQueueManager;
import cn.com.yusys.yusp.admin.Utils.IDUtils;
import cn.com.yusys.yusp.commons.mapper.CommonMapper;
import cn.com.yusys.yusp.commons.service.CommonService;
import cn.com.yusys.yusp.custManager.repository.mapper.MessageSendMapper;
import com.esms.MessageData;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: zoie
 * @Description: 发送短信
 * @Date: 2021/6/25 2:20 下午
 * @Version: 1.0
 */
@Service
public class MessageSendService extends CommonService {
    private static final Logger logger = LoggerFactory.getLogger(MarketCustGroupService.class);
    @Autowired
    private MessageSendMapper messageSendMapper;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    protected CommonMapper getMapper() {
        return this.getMapper();
    }


    /**
     * 查询短信模版
     *
     * @return
     */
    public Map<String, Object> selectMessageTemInfo(String modelType) {
        Map<String, Object> map = messageSendMapper.selectMessageTemInfo(modelType);
        return map;
    }



    /**
     * 获取短信发送一级审核人员
     */
    public List<Map<String, Object>> getApprove(String orgId) {
        String[] roleIdList = new String[]{"R0003", "R0004"};
        List<Map<String, Object>> list = messageSendMapper.getApprove(orgId, roleIdList);
        return list;
    }

    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public void insertApprove(Map map) {
        String modelInfo = map.get("modelInfo").toString();
        String custGroupNo = map.get("custGroupNo").toString();
//        String gridId = map.get("gridId").toString();
        String custMgrId = map.get("userId").toString();
        String approverNo = map.get("approverNo").toString();
        map.put("id", custGroupNo);
        map.put("nodeId", IDUtils.getGuid());
        map.put("approverNo", approverNo);
        map.put("nextNodeId", "");
        map.put("content", modelInfo);
//        map.put("gridId", gridId);
        map.put("custMgrId", custMgrId);
        messageSendMapper.insertApprove(map);
    }

    /**
     * 副行长审批后再生成一条审批节点，支行长审批
     * 支行长审批完，节点结束，发送短信
     *
     * @param map
     */
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public void approveSendMessage(Map map) {
        String roleCode = map.get("roleCode").toString();
        String orgId = map.get("orgId").toString();
//        if ("R0003,R0004".contains(roleCode)) {//副行长
//            map.put("nextNodeId", IDUtils.getGuid());
//            map.put("approvalStatus", "1");
//            messageSendMapper.updateApprove(map);
//            String[] roleIdList = new String[]{"R0005"};
//            List<Map<String, Object>> list = messageSendMapper.getApprove(orgId, roleIdList);
//            String approverNo = list.get(0).get("key").toString();
//            map.put("approverNo", approverNo);
//            map.put("nodeId", map.get("nextNodeId").toString());
//            map.put("nextNodeId", "");
//            map.put("custMgrId", map.get("custMgrId"));
//            messageSendMapper.insertApprove(map);
//        } else if ("R0005".equals(roleCode)) {//支行长
            map.put("nextNodeId", "");
            map.put("approvalStatus", "1");
            messageSendMapper.updateApprove(map);
            //发送短信
            sendMesWait(map.get("id").toString(),map.get("custMgrId").toString(),map.get("content").toString());
//            sendMesWait(map.get("id").toString(),map.get("gridId").toString(),map.get("content").toString());
//        }
    }

    /**
     * 短信调用方法
     */
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public void sendMesWait(String custGroupNo,String custMgrId,String content) {
        List<Map<String, Object>> list = null;
        int count = messageSendMapper.getCount(custGroupNo);
        if (count>0){//客群是下发的
            list = messageSendMapper.selectCusInfoByTask(custGroupNo,custMgrId);
        }else {//客群是客户经理自建的
            list = messageSendMapper.selectCusInfoByGroup(custGroupNo);
        }
        insertSendLog(content,list);
        List<MessageData>  data = list.stream().map(m -> new MessageData(m.getOrDefault("phoneNum", "").toString(), content)).collect(Collectors.toList());
        System.out.println(data.toString());
        if (!data.isEmpty()) {
            try {
                BlockQueueManager.offer(data);//队列入口
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
        }
    }

    /**
     * 添加短信发送日志
     * ExecutorType.BATCH
     * @param content 短信内容
     * @param list
     */
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public void insertSendLog(String content,List<Map<String, Object>> list) {
        String instanceId = IDUtils.getGuid();
        StopWatch watch = new StopWatch();
        watch.start();
        // 步骤1 获取线程批量session
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        // 步骤2 获取mapper
        MessageSendMapper messageSendMapper = session.getMapper(MessageSendMapper.class);
        // 注意，事务内不允许做查询操作，否则无法做事务回滚，因为查询操作会执行flushStatements
        try {
            list.forEach(demo -> {
                demo.put("id", IDUtils.getGuid());
                demo.put("instanceId", instanceId);
                demo.put("content", content);
                messageSendMapper.insertSendLog(demo);
            });
            // 步骤3 推送更新
            session.flushStatements();
            watch.stop();
            logger.info("批量插入成功,{}", watch.shortSummary());
        } catch (Exception e) {
            logger.error("逻辑系统初始化失败，错误信息:{}", e.getMessage());
            throw e;
        }
    }
}
